package com.mcp.mcpserver.service;

import com.mcp.mcpserver.exception.DataSourceException;
import com.mcp.mcpserver.model.DataSourceModel;
import com.mcp.mcpserver.repository.InMemoryDataSourceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;
/**
 * @author zhangxin569
 * @date 2025/8/6
 */
@Service
public class DataSourceManagerService {

    @Autowired
    private InMemoryDataSourceRepository repository;

    public void addDataSource(DataSourceModel config) {
        validateConfig(config);
        testConnection(config);
        repository.save(config);
    }

    public void removeDataSource(String name) {
        repository.deleteByName(name);
    }

    public List<DataSourceModel> listDataSources() {
        return repository.findAll();
    }

    private void validateConfig(DataSourceModel config) {
        if (config.getName() == null || config.getName().isEmpty()) {
            throw new DataSourceException("DataSource name is required");
        }

        if (repository.existsByName(config.getName())) {
            throw new DataSourceException("DataSource '" + config.getName() + "' already exists");
        }

        if (config.getUrl() == null || config.getUrl().isEmpty()) {
            throw new DataSourceException("URL is required");
        }

        if (config.getType() == null ||
                (!"mysql".equalsIgnoreCase(config.getType()) &&
                        !"oceanbase".equalsIgnoreCase(config.getType()))) {
            throw new DataSourceException("Type must be 'mysql' or 'oceanbase'");
        }
    }

    private void testConnection(DataSourceModel config) {
        try (Connection conn = DriverManager.getConnection(
                config.getUrl(),
                config.getUsername(),
                config.getPassword())) {

            if (!conn.isValid(5)) {
                throw new DataSourceException("Connection test failed");
            }
        } catch (Exception e) {
            throw new DataSourceException("Failed to connect to database: " + e.getMessage(), e);
        }
    }
}